
package lxycx.clazz;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

public class NetWorkObject {
	
	private static Logger log = Logger.getLogger(NetworkClassLoader.class);
	private static Map<String,Class>  CLASSS =  new HashMap<String,Class>();//加载过的class池
	private static Map<String,Object>  OBJECTS =  new HashMap<String,Object>();//单例对象池
	private static NetworkClassLoader ncl;
	
	public static void use(String rooturl) {
		ncl = new NetworkClassLoader(rooturl);
	}
	
	public static void use(String rooturl,String encode) {
		ncl = new NetworkClassLoader(rooturl,encode);
	}
	
	/**
	 * 获取单例对象
	 * @param str
	 * @return
	 * @author XingChao
	 * @version 2019年2月1日
	 */
	public static <T> T findSingle(String str){
		if(!OBJECTS.containsKey(str)) {
			if(!CLASSS.containsKey(str)) {
				T t = newInstance(str);
				if(t!=null) {
					OBJECTS.put(str,t);					
				}else {
					return null;
				}
				
			}else {
				try {
					OBJECTS.put(str, CLASSS.get(str).newInstance());
				} catch (Exception e) {
					log.error(str+" 实例化异常",e);
					return null;
				}
			}
		}
		
		try {
			return (T) OBJECTS.get(str);
		} catch (Exception e) {
			log.error(str+" 对象转换异常",e);
			return null;
		}
	}
	
	/**
	 * 实例化一个新的对象
	 * @param str
	 * @return
	 * @author XingChao
	 * @version 2019年2月1日
	 */
	public static <T> T newInstance(String str){
		if(!CLASSS.containsKey(str)) {
			if(ncl!=null) {
				try {
					Class c = ncl.loadClass(str);
					if(c!=null) {
						CLASSS.put(str,c);
					}else {
						log.error("Class加载:对象为空");
						return null;
					}
				} catch (Exception e) {
					log.error("Class加载:"+e);
					return null;
				} catch (Error e) {
					log.error("Class加载:"+e);
					return null;
				}
			}else {
				log.error("请先初始化 rooturl 参数");
				return null;
			}
		}
		
		try {
			return (T) CLASSS.get(str).newInstance();
		} catch (Exception e) {
			log.error(str+" 实例化异常",e);
			return null;
		}			
	}
	

}

